<template>
  <div id="DrugUse">
    <van-nav-bar title="用药情况" left-text="返回" left-arrow @click-left="back" fixed placeholder/>
    <div class="main">
      <div class="content">
        <div class="title">
          口服药物
        </div>
        <div class="srk" v-for="(item, index) in form.yaowu_list" :key="index">
          <van-field
            v-model="item.info"
            rows="12"
            autosize
            type="textarea"
            placeholder="请输入文字"
            maxlength="150"
            show-word-limit
          />
          <div class="upload">
            <span @click="upload(index)">
              
              <van-uploader
                multiple
                v-model="item.filelist"
                :after-read="onRead"
                :before-read="beforeRead"
                :before-delete="deleteImg"
                >
                <van-button type="info" :disabled="disabled">{{btnText}}</van-button>
              </van-uploader>
            </span>
          </div>
        </div>
        <div class="operation">
          <img
            src="@/assets/images/reduce.png"
            alt=""
            @click="reduce"
            v-show="form.yaowu_list.length > 1"
          />
          <img src="@/assets/images/add.png" alt="" @click="add" />
        </div>

        <div class="save">
          <van-button round type="info" :disabled="disabled" @click="save">保存并提交</van-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { upFiles, addMedia } from "@/apis/journal";
import { addHealthLog } from "@/apis/journal";
import apiConfig from "../../../config/api.config";
// 图片压缩
import { uploadImgs } from "../../../config/upload"
export default {
  data() {
    return {
      uploadImgs,
      apiConfig,
      disabled:false,
      btnText:"上传图片",
      form: {
        hzid:null,
        part: 5,
        action:'add',
        yaowu_list: [
          {
            info: "",
            img: []
          }
        ]
      },
      index: "",
      idx:null
    };
  },
  methods: {
    back() {
      this.$router.go(-1); //返回上一层
    },
    upload(index) {
      this.index = index;
    },
    beforeRead(file) {
      if (
        file.type !== "image/jpeg" &&
        file.type !== "image/jpg" &&
        file.type !== "image/gif" &&
        file.type !== "image/png"
      ) {
        this.$toast("请上传 .jpg，.png，.gif 格式图片");
        return false;
      }
      return true;
    },
    onRead(file) {
      this.disabled = true
      this.btnText = "上传中..."
      file.status = 'uploading';
      file.message = '上传中...';
      this.uploadImgs(file)
      setTimeout(()=>{
          if( sessionStorage.getItem('base64') != '' && sessionStorage.getItem('base64')!=null){
          var yaowu = this.form.yaowu_list
          file.index = this.index;
          upFiles({file:sessionStorage.getItem('base64')})
            .then(res => {
            if(res.codes == "200"){
                this.form.yaowu_list[this.index].img.push(res.data);
                file.status = '';
                file.message = '';
                this.add()
                this.reduce()
                this.disabled = false
                this.btnText = "上传图片"
            }else{
              file.status = 'failed';
              file.message = '上传失败';
              this.btnText = "上传图片"
              this.disabled = false
            }
            })
            .catch(err => {
              this.disabled = false
              file.status = 'failed';
              file.message = '上传失败';
              this.btnText = "上传图片"
              this.$toast("上传失败");
              
            });
          sessionStorage.removeItem('base64')
        }else{
          file.status = 'failed';
          file.message = '上传失败';
          this.btnText = "上传图片"
          this.$toast("上传失败");
        }
        },1600)
      // upFiles(file)
      //   .then(res => {
      //      if(res.codes =="200"){
      //         let arr = res.data;
      //         var yaowu = this.form.yaowu_list
      //         file.index = this.index;
      //         arr.forEach(item => {
      //           this.form.yaowu_list[this.index].img.push(item);
      //         });
      //         file.status = '';
      //         file.message = '';
      //         this.add()
      //         this.reduce()
      //         this.disabled = false
      //         this.btnText = "上传图片"
      //      }else{
      //         file.status = 'failed';
      //         this.disabled = false
      //         this.btnText = "上传图片"
      //      }
      //   })
      //   .catch(err => {
      //     file.status = 'failed';
      //     file.message = '上传失败';
      //     this.$toast("上传失败");
      //     this.disabled = false
      //     this.btnText = "上传图片"
      //   });
      //   this.form = this.form
    },
    save() {
      this.form.yaowu_list.forEach(item => {
        delete item.filelist;
      });
      this.form.action='add'
      // 复康日志版本
      this.form.yemian = apiConfig.journal
      addHealthLog(this.form)
        .then(res => {
          this.$toast("添加成功");
          this.$router.go(-1);
          // this.form.id = res.data.id;
          let expire = new Date(
            new Date().setDate(new Date().getDate() + 1)
          ).setHours(0, 0, 0, 0);
          this.localStorageSet("id", res.data.id, expire);
          this.localStorageSet("druguse", this.form, expire);
          // let bool = JSON.stringify(this.form);
          // localStorage.setItem("druguse", bool);
        })
        .catch(err => {
          if(err.msg){
            this.$toast(err.msg);
          }else{
            this.$toast("网络错误"); 
          }
        });
    },
    // 删除图片
   
    deleteImg(detail,$event) {
      console.log($event)
      console.log(detail)
      this.form.yaowu_list.forEach((item,index) =>{
        for (let idx = 0; idx < item.filelist.length; idx++) {
          if( detail.index == item.filelist[idx].index){
            item.filelist.splice($event.index,1)
            item.img.splice($event.index,1)
          break;
          }
        }
      })
      this.add()
      this.reduce()
    },
    reduce() {
      this.form.yaowu_list.pop();
    },
    add() {
      this.form.yaowu_list.push({
        info: "",
        img: []
      });
    }
  },
  mounted() {
    let id = this.localStorageGet("id");
    if (id) {
      this.form.id = id;
    }
    
     addHealthLog({action:'list',id:id,hzid:this.form.hzid})
     .then(res => {
      const data = res.data.list
      for (const i in data) {
        for (const it in this.form) {
          if(i === it) {
            this.form[it] = data[i]
          }
        }
      }
      if(this.form.yaowu_list == null){
        this.form.yaowu_list = [{
            info: "",
            img: []
          }
        ]
      }
      //  this.form.id = id;
      this.form.yaowu_list.forEach((item,index) => {
        item.filelist = [];
        item.img.forEach((el,idx) => {
          el = apiConfig.imgUrl + el.replace(/\\/g, "/");
          item.filelist.push({"url":el,"index":index});
        });
        //
      });
     })
    .catch(err => {
      if(err.msg){
        this.$toast(err.msg);
      }else{
        this.$toast('网络错误');
      }
    });
  },
  created() {
    this.form.hzid = this.$route.params.hzid
  },
};
</script>

<style lang="less">
#DrugUse {
  .van-nav-bar{
    .van-icon,.van-nav-bar__text {
    color: #404040;
    }
  }
  text-align: left;
  .main {
    padding: 10px;
    background-color: #fff;
    .content {
      padding: 17px;
      .title {
        font-size: 18px;
        font-weight: 500;
        margin-bottom: 20px;
      }
      .srk {
        margin-bottom: 10px;
        .van-cell {
          padding: 0;
          background-color: #f5f5f5;
          border-radius: 5px;
          .van-field__control {
            padding: 14px;
          }
        }
        .upload {
          text-align: center;
          margin-top: 20px;
          .van-uploader {
            margin: 10px 0;
            .van-button {
              width: 110px;
              height: 25px;
              border-radius: 55px;
              margin-top: 10px;
            }
          }
          .van-uploader__preview{
            margin: 5px 5px 0;
          }
         .van-uploader{
            width: 85%;
            margin: 0 auto;
          }
          
          .van-uploader__input-wrapper {
            width: 100%;
            position: relative;
          }
        }
      }
      .operation {
        text-align: right;
        img {
          width: 19px;
          &:first-child {
            margin-right: 14px;
          }
        }
      }
      .save {
        margin-top: 50px;
        text-align: center;
        .van-button {
          width: 281px;
          height: 37px;
        }
      }
    }
  }
}
</style>
